package cn.hesion;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
    *@Author hst
    *@Date 19:59 2021/9/7
 **/
public class JavaBatchDemo {

    public static void main(String[] args) throws Exception {
         String input = "data/word.txt";
         String output = "data/output/wordCount";


        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        DataSource<String> data = env.readTextFile(input);
        FlatMapOperator<String, Tuple2<String, Integer>> flatMaped = data.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
                //取到每一行数据
                String[] s1 = s.split(" ");
                //组装成二元组
                for (String s2 : s1) {
                    Tuple2<String, Integer> stringIntegerTuple2 = new Tuple2<>(s2, 1);
                    collector.collect(stringIntegerTuple2);
                }
            }
        });
        UnsortedGrouping<Tuple2<String, Integer>> groupByed = flatMaped.groupBy(0);
        AggregateOperator<Tuple2<String, Integer>> sum = groupByed.sum(1).setParallelism(4);

        //保存
        sum.writeAsText(output);
        sum.print();
//        env.execute();
    }
}
